#include "TrajSave.h"

#include <QString>
#include <QTextStream>
#include <QFile>
#include <cstdlib>

#include "AloneTorque.h"
#include "SpinTorque.h"
#include "TotalTorque.h"
#include "OtherTorque.h"

TrajSave::TrajSave()
{

}

TrajSave::~TrajSave()
{

}

int TrajSave::save(Clock clock,Output output,Pulse *field,Pulse *current,MultiLayer multiLayer)
{
  if(output.getSave()==false)
    return 0;
  else if(output.getSave()==true)
    {
      QFile file(output.getTrajFile());
      QTextStream myfile(&file);
      int layerNumber=multiLayer.getSolveLayer();
      file.open(QIODevice::Append);
      myfile<<clock.getTimeStamp()*1E9;
      myfile<<"\t";
      myfile<<current->getLevel(clock.getTimeStamp())*1000;
      myfile<<"\t";
      myfile<<field->getLevel(clock.getTimeStamp())*1000;
      myfile<<"\t";
      myfile<<multiLayer[layerNumber].getMag().getX();
      myfile<<"\t";
      myfile<<multiLayer[layerNumber].getMag().getY();
      myfile<<"\t";
      myfile<<multiLayer[layerNumber].getMag().getZ();
      myfile<<"\t";
  
      if(multiLayer.getNbFreeLayer()==2)
	{
	  myfile<<"\t";
	  if(multiLayer[layerNumber-1].getFrozen()==false)
	    {
	      myfile<<multiLayer[layerNumber-1].getMag().getX();
	      myfile<<"\t";
	      myfile<<multiLayer[layerNumber-1].getMag().getY();
	      myfile<<"\t";
	      myfile<<multiLayer[layerNumber-1].getMag().getZ();
	    }
	  if(multiLayer[layerNumber+1].getFrozen()==false)
	    {
	      myfile<<multiLayer[layerNumber+1].getMag().getX();
	      myfile<<"\t";
	      myfile<<multiLayer[layerNumber+1].getMag().getY();
	      myfile<<"\t";
	      myfile<<multiLayer[layerNumber+1].getMag().getZ();
	    }
	}
      myfile<<endl;
      file.close();
    }
  return 0;
}

int TrajSave::init(Output output,MultiLayer multiLayer)
{
  if(output.getSave()==false)
    return 0;
  else if(output.getSave()==true)
    {
      /*  //copy Parameters file
      QString command="cp ../Parameters.cc ";
      command+=output.getParamsFile();
      system(command.toAscii().data());
      //copy Polarization file
      command="cp ../SpinTorque.cc ";
      command+=output.getPolarizationFile();
      system(command.toAscii().data());*/
      
      //column titles and units for the output file
      QFile file(output.getFileName());
      QTextStream myfile(&file);
      file.open(QIODevice::Append);
 
      myfile<<"Time\t";
      myfile<<"Current\t";
      myfile<<"Field\t";
      myfile<<"mx\t";
      myfile<<"my\t";
      myfile<<"mz";
      if(multiLayer.getNbLayer()==3)
	{
	  myfile<<"\tmx\t";
	  myfile<<"my\t";
	  myfile<<"mz";
	}
      myfile<<endl;
      myfile<<"ns\t";
      myfile<<"mA\t";
      myfile<<"mT";
      myfile<<endl;
      file.close();
    }
  return 0;
}

